package com.spic.system.annotation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * @author : 赵祥
 * create at:  2022/11/23  16:57
 * @Description :
 **/
public class RangeValidator implements ConstraintValidator<Range, String> {
    private int min;
    private int max;
    private static final String REGEX = "^[-\\+]?[\\d]*$";


    @Override
    public void initialize(Range range) {
        this.min = range.min();
        this.max = range.max();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (value == null) {
            return true;
        }
        //判断是否为纯数字
        Pattern pattern = Pattern.compile(REGEX);
        boolean isNumber = pattern.matcher(value).matches();

        //判断位数是否合法
        int v = Integer.valueOf(value);
        boolean isUp = min <= v;
        boolean isDown = max >= v;
        return isUp && isDown && isNumber;
    }
}
